<?php
/**
 * Created by PhpStorm.
 * User: martin
 * Date: 2018/3/20
 * Time: 16:53
 */

namespace App\Services;

use App\Models\ApplicantThird;
use App\User;
use Laravel\Socialite\Facades\Socialite;

class UserService
{

    //锁定时间
    const LOCK_LOGIN_LIMIT_TIMES = 60;

    /**
     * 验证邮箱是否存在
     *
     * @param string $email
     * @return bool
     */
    public function isExistEmail(string $email)
    {
        $info = User::select(['password', 'id'])
            ->where('email', $email)
            ->first();

        if (!$info) {
            //邮箱不存在
            return false;
        }

        return $info;
    }

    /**
     * 是否有第三方ID
     * @param $provider_id
     * @return bool|mixed
     */
    public function isExistProviderId($provider_id)
    {
        $info = User::select('id','email')->where('provider_id',$provider_id)->first();

        if(!$info){
            return false;
        }
        return $info;
    }

    /**
     * 获取用户信息
     *
     * @param $id
     * @param $need
     * @return mixed
     */
    public function getApplicantInfo($id, $need) {
        return User::select($need)->find($id);
    }

    /**
     * 设置token
     *
     * @param int $userId 用户ID
     * @return string
     */
    public function getToken($userId)
    {
        $token = rand(10000,99999);
        return $token;
    }

    /**
     * 注册用户
     *
     * @param $data
     * @return mixed
     */
    public function doSignUp($data)
    {
        return User::insertGetId($data);
    }

    /**
     * 更新密码
     *
     * @param $id
     * @param $password
     * @return mixed
     */
    public function updatePassword($id, $password)
    {
        return User::where('id', $id)->update(['password' => md5($password)]);
    }

    /**
     * 更新字段
     *
     * @param $where
     * @param $data
     * @return mixed
     */
    public function updateApplicantField($where, $data)
    {
        return User::where($where)->update($data);
    }

    /**
     * 解密邀请码
     *
     * @param $code
     * @return bool|int
     */
    public function getReferrerId($code)
    {
        $code1 = substr($code, 0, -2);
        $code2 = substr($code, -2, 2);
        $uid = $this->getCookieCode($code1);
        if (!$uid) {
            return 0;
        }

        $teacherInfo = Teacher::select('t_pwd')
            ->whereIn('t_status', [1, 3])
            ->where('id', $uid)
            ->first();

        $hexPwd = $this->md5Hex($teacherInfo->t_pwd);
        return ($hexPwd === $code2) ? $uid : 0;
    }

    public function md5Hex($md5)
    {
        $s_arr = array($md5[11], $md5[21]);

        foreach ($s_arr as $s) {
            if (is_numeric($s)) {
                $c_arr[] = intval($s);
            } else {
                $c_arr[] = ord($s);
            }
        }
        $codeNum = dechex($c_arr[0] + $c_arr[1]);
        return (strlen($codeNum) > 1) ? $codeNum : '0' . $codeNum;
    }

    /**
     * 解密
     *
     * @param $code
     * @return bool|int
     */
    public function getCookieCode($code)
    {
        $val = [];
        $arr = str_split($code, 2);
        foreach ($arr as $i => $each) {
            $ord = ord($each[0]);
            if ($ord >= 110) {
                $val[$i] = $ord - 110;
                $rnd = 0;
            } elseif ($ord >= 100) {
                $val[$i] = $ord - 100;
                $rnd = 3;
            } elseif ($ord >= 80) {
                $val[$i] = $ord - 80;
                $rnd = 2;
            } elseif ($ord >= 70) {
                $val[$i] = $ord - 70;
                $rnd = 1;
            }
            if ($rnd != $each[1] % 4)
                return false;
        }
        return intval(strrev(implode($val)));
    }

    /**
     * 第三方登录--注册,返回登录信息 -- 保证邮箱不重复
     * @param string $email
     * @param $provider_id
     * @return array
     */
    public function thirdPartyCallback($email,$provider_id)
    {
        $provider_user = $this->isExistProviderId($provider_id);

        //一个主表id对应一个第三方id
        if(!$provider_user){
            //若该第三方id未关联到主表,添加用户
            $password = rand(100000, 999999);
            $user_id = $this->doSignUp(['email'=>$email,'password'=>$password,'provider_id'=>$provider_id]);
            $email_flag = empty($email)? true:false;
            // todo 发送密码到邮箱
        }else{
            $user_id = $provider_user->id;
            $email_flag = empty($provider_user->email)? true:false;
        }

        $count = 0;
        //登录
        $result = [
            'a_token'       => $this->getToken($user_id),
            'login_time'    => time(),
            'count'         => $count,
            'email'         => $email,
            'email_flag'    => $email_flag
        ];
        return $result;
    }

    //注册用户
    public function registerUser($email,$provider_id)
    {
        return User::insertGetId([
            'email'=>$email,
            'name'=>$email,
            'provider_id'=>$provider_id,
            'create_time'=>date('Y-m-d H:i:s'),
            'update_time'=>date('Y-m-d H:i:s'),
        ]);
    }

}